package com.xylx.interview.loadbalance;

import java.util.Arrays;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * hash负载算法
 * 在一个集群环境下，让同一个用户的访问，分流到固定的一台机器上
 */
public class HashServer {

    public static List<String> list = Arrays.asList("10.180.11.126:8888", "10.180.11.128:8888", "10.180.11.130:8888");

    public static String getServer(String client) {
        int nodeCount = 40;
        TreeMap<Integer, String> treeMap = new TreeMap<>();

        for (String s : list) {
            for (int i = 0; i < nodeCount; i++) {
                treeMap.put((s + "address:" + i).hashCode(), s);
            }
        }

        SortedMap<Integer, String> sortedMap = treeMap.tailMap(client.hashCode());
        Integer firstHash = (sortedMap.size() > 0) ? sortedMap.firstKey() : treeMap.firstKey();
        return treeMap.get(firstHash);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            System.out.println(getServer("用户：" + i + "访问"));
        }
    }
}